import math
import csv
import pandas as pd
from pandas import DataFrame
import numpy as np

from public import PublicData

public_data = PublicData()


def t_merge_sensor_data(df_sensor_data: DataFrame):
    "获取所取样数据的平均值"
    calculate_df = df_sensor_data.drop(['d_date'], axis=1, inplace=False)
    calculate_df['d_time'] = pd.to_datetime(calculate_df['d_time'])
    df_mean = calculate_df.groupby(by="sensor_code").mean().round(3)
    return df_mean


def calculate_agree(end_agree_list: list, sensor_code):
    sensor = public_data.sensor_dic[sensor_code]
    base_agree = sensor.agree_base_agree
    agree_location = sensor.agree
    index = 0
    if agree_location == "y":
        index = 1
    agree = round(abs(end_agree_list[index] - base_agree[index]), 2)
    return [agree, end_agree_list[index+3]]


def get_start_value(df_data: DataFrame):
    """获取初始的数据值"""
    df_calculate_data = df_data.drop(["d_time", "acc_x", "acc_y", "acc_z", "gyro_x", "gyro_y",
                                      "gyro_z", "mag_x", "mag_y", "mag_z", "acc_x", "temp", "bat", "rss"], axis=1,
                                     inplace=False)

    df_std = df_calculate_data.groupby(by="sensor_code").std().round(4)
    is_first_status = list((df_std[["angle_x", "angle_y", "angle_z"]] < 0.1).all())
    if False not in is_first_status:
        df_mean = df_calculate_data.groupby(by="sensor_code").mean().round(3)
        return df_mean
    return None


def calculate_bend_degree(df_now_data: DataFrame, writer=None):
    """计算转动的角度"""
    end_row_index = df_now_data.index
    bend_degree_dic = dict()

    for sensor_code in end_row_index:
        end_degree_list = list(df_now_data.loc[sensor_code, ["angle_x", "angle_y", "angle_z","acc_x", "acc_y", "acc_z"]])

        bend_degree_dic[sensor_code] =calculate_agree(end_degree_list, sensor_code)
        # 写入数据s
        # if writer:
        #     writer.writerow([index, *end_degree_list, bend_degree_dic[index]])
    return bend_degree_dic
